import type { CascaderOptions, CascaderOptionsData } from '../../types/options';
import { query } from '../utils/query';

/**
 * 菜单管理器
 * 负责级联选择器的菜单显示、隐藏和创建
 */
export class MenuManager {
    private uuid: string;
    private splitStr: string;
    private options: CascaderOptions;

    constructor(uuid: string, splitStr: string, options: CascaderOptions) {
        this.uuid = uuid;
        this.splitStr = splitStr;
        this.options = options;
    }

    /**
     * 显示菜单
     */
    public menusShow() {
        const { mode = "single" } = this.options;

        if (mode !== "multiple") {
            // 注意：这里需要调用setValue，但由于我们正在拆分，所以暂时留空
            // 后续重构时需要通过依赖注入或回调函数解决
        }

        query(`.cascader-container_${this.uuid}`, this.uuid, true)?.classList.add("cascader-container_active");
        query(".cascader-container_menus", this.uuid)?.classList.add("cascader-container_menus_active");
    }

    /**
     * 隐藏菜单
     */
    public menusHide() {
        query(`.cascader-container_${this.uuid}`, this.uuid, true)?.classList.remove("cascader-container_active");
        query(".cascader-container_menus", this.uuid)?.classList.remove("cascader-container_menus_active");
    }

    /**
     * 创建菜单
     * @param data 菜单数据
     * @param level 菜单级别
     * @param tag 菜单标签
     */
    public createMenu(data: CascaderOptionsData[] = [], level: number = 0, tag: string = "") {
        const { mode = "single" } = this.options;

        let html = `<div class="cascader-container_menus_menu" data-level="${level}">`;

        for (let index = 0; index < data.length; index++) {
            const { className, showTitle, disabled, children = [], label, value } = data[index];

            const otherClass = `${className ? ` ${className}` : ""}${disabled ? " cascader-container_menus_menu_item_disabled" : ""}`;

            const tagStr = tag ? `${tag}${this.splitStr}${value}` : value;

            const multipleisDisabled = disabled ? "cascader-container_menus_menu_item_multiple_disabled" : "";

            const isMultiple = 
                mode === "multiple"
                    ? `
                        <div class="cascader-container_menus_menu_item_multiple ${multipleisDisabled}">
                            <div>
                                <span>&radic;</span>
                            </div>
                        </div>
                    `
                    : ``;

            html += `
                    <div class="cascader-container_menus_menu_item${otherClass}" data-parent-level="${level}" data-label="${label}" data-value="${value}" data-tag="${tagStr}">
                        ${isMultiple}
                        <div
                            class="cascader-container_menus_menu_item_value"
                            ${showTitle ? `title="${label}"` : ``}
                        >
                            ${label}
                        </div>
                        <div class="cascader-container_menus_menu_item_icon">
                            ${children.length ? ">" : ""}
                        </div>
                    </div>
                `;
        }

        html += `</div>`;

        query(".cascader-container_menus", this.uuid)?.insertAdjacentHTML("beforeend", html);
    }

    /**
     * 搜索框已在Cascader.ts中直接创建，此方法不再使用
     */
    public createSearchBox() {
        console.warn('createSearchBox method is deprecated, search box is now created in Cascader.ts');
    }

    /**
     * 显示搜索结果
     * @param results 搜索结果
     * @param searchKeyword 搜索关键词
     */
    public showSearchResults(results: Array<{data: CascaderOptionsData, path: string[]}>, searchKeyword: string) {
        // 清空现有菜单
        this.resetMenu();
        
        // 创建搜索结果菜单
        let html = `<div class="cascader-container_menus_search_result">`;
        
        if (results.length === 0) {
            // 无搜索结果
            html += `
                <div class="cascader-container_menus_search_result_empty">
                    未找到与 "${searchKeyword}" 相关的结果
                </div>
            `;
        } else {
            // 显示搜索结果
            for (const result of results) {
                const { data: { label, value, disabled } } = result;
                const pathStr = result.path.join(this.splitStr);
                
                // 高亮匹配的关键字
                const highlightedLabel = this.highlightKeyword(label, searchKeyword);
                
                html += `
                    <div 
                        class="cascader-container_menus_search_result_item ${disabled ? 'cascader-container_menus_search_result_item_disabled' : ''}" 
                        data-value="${value}" 
                        data-path="${pathStr}"
                    >
                        ${highlightedLabel}
                    </div>
                `;
            }
        }
        
        html += `</div>`;
        
        // 添加搜索结果到菜单容器
        query(".cascader-container_menus", this.uuid)?.insertAdjacentHTML("beforeend", html);
    }
    
    /**
     * 高亮匹配的关键字
     * @param text 原始文本
     * @param keyword 关键字
     * @returns 高亮后的HTML
     */
    private highlightKeyword(text: string, keyword: string): string {
        if (!keyword || !text) {
            return text;
        }
        
        // 转义正则表达式特殊字符
        const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        
        // 创建不区分大小写的正则表达式
        const regex = new RegExp(`(${escapedKeyword})`, 'gi');
        
        // 使用<span>标签包裹匹配的关键字并添加高亮样式
        return text.replace(regex, '<span class="cascader-container_menus_search_result_item_highlight">$1</span>');
    }

    /**
     * 重置菜单到初始状态
     */
    public resetMenu() {
        const menuContainer = query(".cascader-container_menus", this.uuid);
        if (menuContainer) {
            // 直接清空菜单内容，搜索框已在外部
            menuContainer.innerHTML = '';
        }
    }

    /**
     * 清空搜索框
     */
    public clearSearchBox() {
        const searchInput = query(".cascader-container_search_input", this.uuid) as HTMLInputElement;
        if (searchInput) {
            searchInput.value = '';
        }
        
        // 隐藏清空按钮
        const clearBtn = query(".cascader-container_search_clear", this.uuid);
        if (clearBtn) {
            clearBtn.style.display = 'none';
        }
    }

    /**
     * 设置搜索框值
     * @param keyword 搜索关键词
     */
    public setSearchBoxValue(keyword: string) {
        const searchInput = query(".cascader-container_search_input", this.uuid) as HTMLInputElement;
        if (searchInput) {
            searchInput.value = keyword;
            
            // 显示/隐藏清空按钮
            const clearBtn = query(".cascader-container_search_clear", this.uuid);
            if (clearBtn) {
                clearBtn.style.display = keyword ? 'flex' : 'none';
            }
        }
    }
}